package org.bjou

import org.springframework.dao.DataIntegrityViolationException
import java.util.Locale
import java.text.*
import org.apache.shiro.web.util.SavedRequest
import org.apache.shiro.web.util.WebUtils

class BranchCourseController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
        
        def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
       def deadline = Config.findByConfigKey('branchForecast')?.configValue
        
        def round = Config.findByConfigKey('round')?.configValue
        
        def strRound = (round=="forecast")?"预报":"正报"
        
        if (!params.max) params.max = 10  
        if (!params.offset) params.offset = 0  
        if (!params.sort) params.sort = "id"  
        if (!params.order) params.order = "asc" 
        if (!session.admin)
        {
            if (!params.branchId) params.branchId = session.branch.id
            params.branchFlag = true
        }
        if (!params.currentTerm) params.currentTerm = currentTerm
        
       
        def cel = { 
            
            if(params.ruleCode){  
                like("ruleCode", "%${params.ruleCode}%")  
            }
            if(params.majorName){  
                like("majorName", "%${params.majorName}%")  
            }
            if(params.courseId){  
                like("courseId", "%${params.courseId}%")  
            }
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
            if(params.courseType){  
                like("courseType", "%${params.courseType}%")  
            }
            if(params.courseProperty){  
                like("courseProperty", "%${params.courseProperty}%")  
            }
            if(params.examType){  
                like("examType", "%${params.examType}%")  
            }
            if(params.departmentName){  
                like("departmentName", "%${params.departmentName}%")  
            }
            if(params.majorLevel){  
                like("majorLevel", "%${params.majorLevel}%")  
            }
            if(params.courseStatus){  
                like("courseStatus", "%${params.courseStatus}%")  
            }
            
            if(params.branchId){
                sqlRestriction ("id in(select course_id from branch_course where current_Term = '"+params.currentTerm +"' and branch_id ="+params.branchId+")"  )
            }
            
            
        }  
        
        def courseList = Course.createCriteria().list(params,cel) 
        def tocJson=[]
        courseList.each{ ch ->
            println ch
            def chJson= [:]
            ch.getProperties().each { property ->
                 chJson.put property.key, property.value
        
            }
            
            if(params.branchId){
                def branchInstance = Branch.get(params.branchId)
                def brancheCourseOfficialInstance = BranchCourse.findByCourseAndBranchAndCurrentTermAndRound(ch,branchInstance,currentTerm,"official")
                def brancheCourseForcastInstance = BranchCourse.findByCourseAndBranchAndCurrentTermAndRound(ch,branchInstance,currentTerm,"forecast")
                def brancheCourseInstance
                if(brancheCourseOfficialInstance!=null&&brancheCourseForcastInstance!=null)
                {
                     chJson['roundFlag'] = "预正报"
                     brancheCourseInstance = brancheCourseOfficialInstance
                }
                else if(brancheCourseOfficialInstance==null&&brancheCourseForcastInstance!=null)
                 {
                     chJson['roundFlag'] = "预报"
                     brancheCourseInstance = brancheCourseForcastInstance
                  }
                 else if(brancheCourseOfficialInstance!=null&&brancheCourseForcastInstance==null)
                 {
                      chJson['roundFlag'] = "正报"
                      brancheCourseInstance = brancheCourseOfficialInstance
                 }
                 else
                 {
                     chJson['roundFlag'] = ""
                 }
                 
               
                chJson['teacherName'] =brancheCourseInstance?.teacherName
                 chJson['teacherTitle'] = brancheCourseInstance?.teacherTitle
                 chJson['teacherTel'] = brancheCourseInstance?.teacherTel
                 chJson['teacherQty'] = brancheCourseInstance?.teacherQty
                 chJson['id'] =brancheCourseInstance?.id
            }
           
         
            
            tocJson << chJson
        }
        def totalRows = Course.createCriteria().list(cel).size()
         
        //println tocJson
        
        // def courseList = Course.findAll("from Course where id in(select course.id from BranchCourse)")
   
        
        
        [courseInstanceList: tocJson, courseInstanceTotal: totalRows,deadline:deadline,round:strRound]
        
    }
    
   def exportList()
    {
       def currentTerm = Config.findByConfigKey('currentTerm')?.configValue
       def deadline = Config.findByConfigKey('branchForecast')?.configValue
        
        def round = Config.findByConfigKey('round')?.configValue
        
        def strRound = (round=="forecast")?"预报":"正报"
        
       
        if (!params.offset) params.offset = 0  
        if (!params.sort) params.sort = "id"  
        if (!params.order) params.order = "asc" 
        if (!session.admin)
        {
            if (!params.branchId) params.branchId = session.branch.id
            params.branchFlag = true
        }
        if (!params.currentTerm) params.currentTerm = currentTerm
        
       
        def cel = { 
            
            if(params.ruleCode){  
                like("ruleCode", "%${params.ruleCode}%")  
            }
            if(params.majorName){  
                like("majorName", "%${params.majorName}%")  
            }
            if(params.courseId){  
                like("courseId", "%${params.courseId}%")  
            }
            if(params.courseName){  
                like("courseName", "%${params.courseName}%")  
            }
            if(params.courseType){  
                like("courseType", "%${params.courseType}%")  
            }
            if(params.courseProperty){  
                like("courseProperty", "%${params.courseProperty}%")  
            }
            if(params.examType){  
                like("examType", "%${params.examType}%")  
            }
            if(params.departmentName){  
                like("departmentName", "%${params.departmentName}%")  
            }
            if(params.majorLevel){  
                like("majorLevel", "%${params.majorLevel}%")  
            }
            if(params.courseStatus){  
                like("courseStatus", "%${params.courseStatus}%")  
            }
            
            if(params.branchId){
                sqlRestriction ("id in(select course_id from branch_course where current_Term = '"+params.currentTerm +"' and branch_id ="+params.branchId+")"  )
            }
            
            
        }  
        
        def courseList = Course.createCriteria().list(params,cel) 
        def tocJson=[]
        courseList.each{ ch ->
            println ch
            def chJson= [:]
            ch.getProperties().each { property ->
                 chJson.put property.key, property.value
        
            }
            
            if(params.branchId){
                def branchInstance = Branch.get(params.branchId)
                def brancheCourseOfficialInstance = BranchCourse.findByCourseAndBranchAndCurrentTermAndRound(ch,branchInstance,currentTerm,"official")
                def brancheCourseForcastInstance = BranchCourse.findByCourseAndBranchAndCurrentTermAndRound(ch,branchInstance,currentTerm,"forecast")
                def brancheCourseInstance
                if(brancheCourseOfficialInstance!=null&&brancheCourseForcastInstance!=null)
                {
                     chJson['roundFlag'] = "预正报"
                     brancheCourseInstance = brancheCourseOfficialInstance
                }
                else if(brancheCourseOfficialInstance==null&&brancheCourseForcastInstance!=null)
                 {
                     chJson['roundFlag'] = "预报"
                     brancheCourseInstance = brancheCourseForcastInstance
                  }
                 else if(brancheCourseOfficialInstance!=null&&brancheCourseForcastInstance==null)
                 {
                      chJson['roundFlag'] = "正报"
                      brancheCourseInstance = brancheCourseOfficialInstance
                 }
                 else
                 {
                     chJson['roundFlag'] = ""
                 }
                 
               
                chJson['teacherName'] =brancheCourseInstance?.teacherName
                 chJson['teacherTitle'] = brancheCourseInstance?.teacherTitle
                 chJson['teacherTel'] = brancheCourseInstance?.teacherTel
                 chJson['teacherQty'] = brancheCourseInstance?.teacherQty
            }
           
         
            
            tocJson << chJson
        }
        
        
        def sdf = new SimpleDateFormat("yyyyMMddHHmmss")
        XlsExportService xlsExportService = new XlsExportService();  
        response.setHeader("Content-disposition", "attachment; filename="+sdf.format(new Date())+".xls")
        response.setContentType("application/vnd.ms-excel")
        xlsExportService.branchPickExport(response.outputStream, tocJson)
    } 

    def create() {
        [branchCourseInstance: new BranchCourse(params)]
    }

    def save() {
        println params
        
        //判断是否数字
        if(!params.teacherQty.isInteger())
        {
            flash.message="请输入数字"
            return
        }
        
        
        
        def branchCourseInstance = new BranchCourse(params)
        if (!branchCourseInstance.save(flush: true)) {
           
            render(view: "create", model: [branchCourseInstance: branchCourseInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'branchCourse.label', default: 'BranchCourse'), branchCourseInstance.course.courseName])
        redirect(action: "show", id: branchCourseInstance.id)
    }

    def show() {
        def branchCourseInstance = BranchCourse.get(params.id)
        if (!branchCourseInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'branchCourse.label', default: 'BranchCourse'), params.id])
            redirect(action: "list")
            return
        }

        [branchCourseInstance: branchCourseInstance]
    }

    def edit() {
        print("id="+params.id)
        def branchCourseInstance = BranchCourse.get(params.id)
        if (!branchCourseInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'branchCourse.label', default: 'BranchCourse'), params.id])
            redirect(action: "list")
            return
        }

        [branchCourseInstance: branchCourseInstance]
    }

    def update() {
        def branchCourseInstance = BranchCourse.get(params.id)
        
        println params.teacherQty.isInteger()
        
        //判断是否数字
        if(!params.teacherQty.isInteger())
        {
            flash.message="请输入数字"
            render(view: "edit", model: [branchCourseInstance: branchCourseInstance])
            return
        }
        
        if (!branchCourseInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'branchCourse.label', default: 'BranchCourse'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (branchCourseInstance.version > version) {
                branchCourseInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                    [message(code: 'branchCourse.label', default: 'BranchCourse')] as Object[],
                          "Another user has updated this BranchCourse while you were editing")
                render(view: "edit", model: [branchCourseInstance: branchCourseInstance])
                return
            }
        }

        branchCourseInstance.properties = params
        
       

        if (!branchCourseInstance.save(flush: true)) {
            flash.message = "保存失败"
            render(view: "edit", model: [branchCourseInstance: branchCourseInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'branchCourse.label', default: 'BranchCourse'), branchCourseInstance.course.courseName])
        redirect(action: "show", id: branchCourseInstance.id)
    }

    def delete() {
        def branchCourseInstance = BranchCourse.get(params.id)
        if (!branchCourseInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'branchCourse.label', default: 'BranchCourse'), params.id])
            redirect(action: "list")
            return
        }

        try {
            branchCourseInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'branchCourse.label', default: 'BranchCourse'), branchCourseInstance.course.courseName])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'branchCourse.label', default: 'BranchCourse'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
}
